"""
AI历史消息记忆管理路由
"""

from datetime import datetime
from typing import List, Optional

from fastapi import APIRouter, HTTPException, Query, Depends, Body
from sqlalchemy import and_, or_, desc
from sqlalchemy.orm import Session, joinedload

from config.database import get_db_session
from pojo.ai_web_agent_model import AIWebAgentModel
from pojo.ai_web_memory_his import (
    AIWebMemoryHisCreate, AIWebMemoryHisUpdate, AIWebMemoryHisResponse,
    AIWebMemoryHisListResponse, AIWebMemoryHisQueryParams, AIWebMemoryHisStatusUpdate,
    AIWebMemoryHisImportanceUpdate, AIWebMemoryHisBatchUpdate, AIWebMemoryHisBatchDelete,
    AIWebMemoryHisBatchDeleteByDate, AIWebMemoryHisStatistics
)
from pojo.ai_web_memory_his_model import AIWebMemoryHisModel
from pojo.ai_web_scene_model import AIWebSceneModel

router = APIRouter()


def get_memory_query(db: Session, query_params: AIWebMemoryHisQueryParams):
    """构建查询条件"""
    # 创建基础查询，包含场景和智能体的关联
    query = db.query(AIWebMemoryHisModel) \
        .outerjoin(AIWebSceneModel, AIWebMemoryHisModel.scene_id == AIWebSceneModel.scene_id) \
        .outerjoin(AIWebAgentModel, AIWebMemoryHisModel.agent_id == AIWebAgentModel.agent_id)

    # 基本筛选条件
    if query_params.scene_id:
        query = query.filter(AIWebMemoryHisModel.scene_id == query_params.scene_id)
    if query_params.agent_id:
        query = query.filter(AIWebMemoryHisModel.agent_id == query_params.agent_id)

    # 新增：按场景名称和智能体名称筛选
    if query_params.scene_name:
        query = query.filter(AIWebSceneModel.scene_name.like(f"%{query_params.scene_name}%"))
    if query_params.agent_name:
        query = query.filter(AIWebAgentModel.agent_name.like(f"%{query_params.agent_name}%"))

    if query_params.session_id:
        query = query.filter(AIWebMemoryHisModel.session_id == query_params.session_id)
    if query_params.user_id:
        query = query.filter(AIWebMemoryHisModel.user_id == query_params.user_id)
    if query_params.status is not None:
        query = query.filter(AIWebMemoryHisModel.status == query_params.status)
    if query_params.importance_level is not None:
        query = query.filter(AIWebMemoryHisModel.importance_level == query_params.importance_level)

    # 标签筛选（包含匹配）
    if query_params.tags:
        query = query.filter(AIWebMemoryHisModel.tags.like(f"%{query_params.tags}%"))

    # 关键词搜索（搜索消息内容、标注内容）
    if query_params.keyword:
        keyword_filter = or_(
            AIWebMemoryHisModel.his_text.like(f"%{query_params.keyword}%"),
            AIWebMemoryHisModel.annotation.like(f"%{query_params.keyword}%")
        )
        query = query.filter(keyword_filter)

    # 时间范围筛选
    if query_params.start_time:
        query = query.filter(AIWebMemoryHisModel.create_time >= query_params.start_time)
    if query_params.end_time:
        query = query.filter(AIWebMemoryHisModel.create_time <= query_params.end_time)

    return query


@router.get("/", response_model=AIWebMemoryHisListResponse, summary="获取历史消息记忆列表")
async def get_memory_list(
        page: int = Query(1, ge=1, description="页码"),
        page_size: int = Query(20, ge=1, le=100, description="每页数量"),
        scene_id: Optional[str] = Query(None, description="场景ID筛选"),
        agent_id: Optional[str] = Query(None, description="智能体ID筛选"),
        scene_name: Optional[str] = Query(None, description="场景名称筛选"),
        agent_name: Optional[str] = Query(None, description="智能体名称筛选"),
        session_id: Optional[str] = Query(None, description="对话ID筛选"),
        user_id: Optional[str] = Query(None, description="用户ID筛选"),
        status: Optional[int] = Query(None, description="状态筛选"),
        importance_level: Optional[int] = Query(None, description="重要程度筛选"),
        tags: Optional[str] = Query(None, description="标签筛选"),
        keyword: Optional[str] = Query(None, description="关键词搜索"),
        start_time: Optional[datetime] = Query(None, description="开始时间"),
        end_time: Optional[datetime] = Query(None, description="结束时间"),
        db: Session = Depends(get_db_session)
):
    """获取历史消息记忆分页列表"""
    try:
        # 构建查询参数
        query_params = AIWebMemoryHisQueryParams(
            scene_id=scene_id,
            agent_id=agent_id,
            scene_name=scene_name,
            agent_name=agent_name,
            session_id=session_id,
            user_id=user_id,
            status=status,
            importance_level=importance_level,
            tags=tags,
            keyword=keyword,
            start_time=start_time,
            end_time=end_time
        )

        # 构建查询
        query = get_memory_query(db, query_params)

        # 获取总数
        total = query.count()

        # 分页和排序，同时加载关联的场景和智能体信息
        items = query.options(
            joinedload(AIWebMemoryHisModel.scene),
            joinedload(AIWebMemoryHisModel.agent)
        ).order_by(desc(AIWebMemoryHisModel.create_time)) \
            .offset((page - 1) * page_size) \
            .limit(page_size) \
            .all()

        # 转换为响应模型
        memory_list = []
        for item in items:
            # 获取关联的场景和智能体名称
            scene_name = item.scene.scene_name if item.scene else None
            agent_name = item.agent.agent_name if item.agent else None

            memory_response = AIWebMemoryHisResponse(
                id=item.id,
                scene_id=item.scene_id,
                agent_id=item.agent_id,
                scene_name=scene_name,
                agent_name=agent_name,
                session_id=item.session_id,
                user_id=item.user_id,
                his_text=item.his_text,
                create_time=item.create_time,
                update_time=item.update_time,
                status=item.status,
                importance_level=item.importance_level,
                tags=item.tags,
                annotation=item.annotation,
                extra_info=item.get_extra_info()
            )
            memory_list.append(memory_response)

        return AIWebMemoryHisListResponse(
            total=total,
            items=memory_list
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取记忆列表失败: {str(e)}")


@router.get("/{memory_id}", response_model=AIWebMemoryHisResponse, summary="获取单个历史消息记忆")
async def get_memory_by_id(
        memory_id: int,
        db: Session = Depends(get_db_session)
):
    """根据ID获取单个历史消息记忆"""
    memory = db.query(AIWebMemoryHisModel).filter(AIWebMemoryHisModel.id == memory_id).first()

    if not memory:
        raise HTTPException(status_code=404, detail="记忆不存在")

    return AIWebMemoryHisResponse(
        id=memory.id,
        scene_id=memory.scene_id,
        agent_id=memory.agent_id,
        session_id=memory.session_id,
        user_id=memory.user_id,
        his_text=memory.his_text,
        create_time=memory.create_time,
        update_time=memory.update_time,
        status=memory.status,
        importance_level=memory.importance_level,
        tags=memory.tags,
        annotation=memory.annotation,
        extra_info=memory.get_extra_info()
    )


@router.post("/", response_model=AIWebMemoryHisResponse, summary="创建历史消息记忆")
async def create_memory(
        memory_create: AIWebMemoryHisCreate,
        db: Session = Depends(get_db_session)
):
    """创建新的历史消息记忆"""
    try:
        # 创建数据库模型实例
        memory_model = AIWebMemoryHisModel(
            scene_id=memory_create.scene_id,
            agent_id=memory_create.agent_id,
            session_id=memory_create.session_id,
            user_id=memory_create.user_id,
            his_text=memory_create.his_text,
            status=memory_create.status,
            importance_level=memory_create.importance_level,
            tags=memory_create.tags,
            annotation=memory_create.annotation,
            create_time=datetime.now()
        )

        # 设置扩展信息
        if memory_create.extra_info:
            memory_model.set_extra_info(memory_create.extra_info)

        # 保存到数据库
        db.add(memory_model)
        db.commit()
        db.refresh(memory_model)

        return AIWebMemoryHisResponse(
            id=memory_model.id,
            scene_id=memory_model.scene_id,
            agent_id=memory_model.agent_id,
            session_id=memory_model.session_id,
            user_id=memory_model.user_id,
            his_text=memory_model.his_text,
            create_time=memory_model.create_time,
            update_time=memory_model.update_time,
            status=memory_model.status,
            importance_level=memory_model.importance_level,
            tags=memory_model.tags,
            annotation=memory_model.annotation,
            extra_info=memory_model.get_extra_info()
        )

    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"创建记忆失败: {str(e)}")


@router.put("/{memory_id}", response_model=AIWebMemoryHisResponse, summary="更新历史消息记忆")
async def update_memory(
        memory_id: int,
        memory_update: AIWebMemoryHisUpdate,
        db: Session = Depends(get_db_session)
):
    """更新历史消息记忆"""
    try:
        memory = db.query(AIWebMemoryHisModel).filter(AIWebMemoryHisModel.id == memory_id).first()

        if not memory:
            raise HTTPException(status_code=404, detail="记忆不存在")

        # 更新字段
        update_data = memory_update.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            if field == "extra_info":
                memory.set_extra_info(value)
            else:
                setattr(memory, field, value)

        memory.update_time = datetime.now()

        db.commit()
        db.refresh(memory)

        return AIWebMemoryHisResponse(
            id=memory.id,
            scene_id=memory.scene_id,
            agent_id=memory.agent_id,
            session_id=memory.session_id,
            user_id=memory.user_id,
            his_text=memory.his_text,
            create_time=memory.create_time,
            update_time=memory.update_time,
            status=memory.status,
            importance_level=memory.importance_level,
            tags=memory.tags,
            annotation=memory.annotation,
            extra_info=memory.get_extra_info()
        )

    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"更新记忆失败: {str(e)}")


@router.delete("/{memory_id}", summary="删除历史消息记忆（包括内存中的记忆）")
async def delete_memory(
        memory_id: int,
        db: Session = Depends(get_db_session)
):
    """删除单个历史消息记忆（包括内存中的记忆）"""
    try:
        memory = db.query(AIWebMemoryHisModel).filter(AIWebMemoryHisModel.id == memory_id).first()

        if not memory:
            raise HTTPException(status_code=404, detail="记忆不存在")

        # 获取记忆信息用于清除内存记忆
        session_id = memory.session_id
        scene_id = memory.scene_id
        agent_id = memory.agent_id
        user_id = memory.user_id

        # 删除数据库记录
        db.delete(memory)
        db.commit()

        # 清除内存中的记忆
        try:
            from memory.MemoryManager import MemoryManager

            # 创建MemoryManager实例来清除记忆
            memory_manager = MemoryManager(
                db_session=db,
                scene_id=scene_id,
                agent_id=agent_id,
                session_id=session_id,
                user_id=user_id
            )

            # 清除所有内存记忆（LangChain + Mem0）
            clear_success = memory_manager.clear_memory(clear_db=False, clear_mem0=True)
            if clear_success:
                print(f"✅ 成功清除session {session_id} 的内存记忆")
            else:
                print(f"⚠️ 清除session {session_id} 的内存记忆时出现部分问题")

        except Exception as memory_error:
            print(f"⚠️ 清除内存记忆失败: {memory_error}")
            # 内存记忆清除失败不影响数据库删除的成功

        return {"message": f"记忆 {memory_id} 删除成功（包括内存记忆）"}

    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"删除记忆失败: {str(e)}")


@router.post("/batch_update", summary="批量更新历史消息记忆")
async def batch_update_memory(
        batch_update: AIWebMemoryHisBatchUpdate,
        db: Session = Depends(get_db_session)
):
    """批量更新历史消息记忆"""
    try:
        # 查询要更新的记录
        memories = db.query(AIWebMemoryHisModel).filter(
            AIWebMemoryHisModel.id.in_(batch_update.ids)
        ).all()

        if not memories:
            raise HTTPException(status_code=404, detail="没有找到要更新的记忆")

        # 批量更新
        update_count = 0
        for memory in memories:
            if batch_update.status is not None:
                memory.update_status(batch_update.status)
                update_count += 1
            if batch_update.importance_level is not None:
                memory.update_importance(batch_update.importance_level)
                update_count += 1
            if batch_update.tags is not None:
                memory.tags = batch_update.tags
                memory.update_time = datetime.now()
                update_count += 1

        db.commit()

        return {"message": f"成功更新 {len(memories)} 条记忆"}

    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"批量更新失败: {str(e)}")


@router.post("/batch_delete", summary="批量删除历史消息记忆（包括内存中的记忆）")
async def batch_delete_memory(
        batch_delete_request: AIWebMemoryHisBatchDelete = Body(...),
        db: Session = Depends(get_db_session)
):
    """批量删除历史消息记忆（包括内存中的记忆）"""
    try:
        ids = batch_delete_request.ids

        # 获取要删除的记忆信息
        memories_to_delete = db.query(AIWebMemoryHisModel).filter(
            AIWebMemoryHisModel.id.in_(ids)
        ).all()

        if not memories_to_delete:
            raise HTTPException(status_code=404, detail="没有找到要删除的记忆")

        # 收集唯一的session信息用于清除内存记忆
        sessions_to_clear = {}
        for memory in memories_to_delete:
            session_key = f"{memory.scene_id}:{memory.agent_id}:{memory.session_id}:{memory.user_id}"
            if session_key not in sessions_to_clear:
                sessions_to_clear[session_key] = {
                    "scene_id": memory.scene_id,
                    "agent_id": memory.agent_id,
                    "session_id": memory.session_id,
                    "user_id": memory.user_id
                }

        # 删除数据库记录
        deleted_count = db.query(AIWebMemoryHisModel).filter(
            AIWebMemoryHisModel.id.in_(ids)
        ).delete(synchronize_session=False)

        db.commit()

        # 清除相关会话的内存记忆
        cleared_sessions = 0
        try:
            from memory.MemoryManager import MemoryManager

            for session_info in sessions_to_clear.values():
                try:
                    memory_manager = MemoryManager(
                        db_session=db,
                        scene_id=session_info["scene_id"],
                        agent_id=session_info["agent_id"],
                        session_id=session_info["session_id"],
                        user_id=session_info["user_id"]
                    )

                    # 清除所有内存记忆
                    if memory_manager.clear_memory(clear_db=False, clear_mem0=True):
                        cleared_sessions += 1
                        print(f"✅ 成功清除session {session_info['session_id']} 的内存记忆")

                except Exception as session_error:
                    print(f"⚠️ 清除session {session_info['session_id']} 内存记忆失败: {session_error}")

        except Exception as memory_error:
            print(f"⚠️ 批量清除内存记忆失败: {memory_error}")

        return {
            "message": f"成功删除 {deleted_count} 条记忆，清除了 {cleared_sessions} 个会话的内存记忆",
            "deleted_count": deleted_count,
            "cleared_sessions": cleared_sessions
        }

    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"批量删除失败: {str(e)}")


@router.post("/batch_delete_by_date", summary="按日期批量删除历史消息记忆（包括内存中的记忆）")
async def batch_delete_by_date(
        batch_delete_request: AIWebMemoryHisBatchDeleteByDate = Body(...),
        db: Session = Depends(get_db_session)
):
    """按日期和条件批量删除历史消息记忆（包括内存中的记忆）"""
    try:
        # 解析日期字符串为datetime对象
        try:
            from datetime import datetime as dt
            # 尝试解析多种日期格式
            date_formats = [
                "%Y-%m-%d %H:%M:%S",  # 前端格式: 2024-01-01 10:30:00
                "%Y-%m-%dT%H:%M:%S",  # ISO格式: 2024-01-01T10:30:00
                "%Y-%m-%d",  # 仅日期: 2024-01-01
            ]

            parsed_start_date = None
            parsed_end_date = None

            for fmt in date_formats:
                try:
                    parsed_start_date = dt.strptime(batch_delete_request.start_date, fmt)
                    break
                except ValueError:
                    continue

            for fmt in date_formats:
                try:
                    parsed_end_date = dt.strptime(batch_delete_request.end_date, fmt)
                    break
                except ValueError:
                    continue

            if parsed_start_date is None:
                raise HTTPException(status_code=422, detail=f"无法解析开始日期格式: {batch_delete_request.start_date}")
            if parsed_end_date is None:
                raise HTTPException(status_code=422, detail=f"无法解析结束日期格式: {batch_delete_request.end_date}")

        except Exception as date_error:
            raise HTTPException(status_code=422, detail=f"日期解析失败: {str(date_error)}")

        # 构建基础查询
        query = db.query(AIWebMemoryHisModel)

        # 添加场景关联（如果需要按场景名称筛选）
        if batch_delete_request.scene_name:
            query = query.join(AIWebSceneModel, AIWebMemoryHisModel.scene_id == AIWebSceneModel.scene_id)
            query = query.filter(AIWebSceneModel.scene_name.like(f"%{batch_delete_request.scene_name}%"))
        elif batch_delete_request.scene_id:
            query = query.filter(AIWebMemoryHisModel.scene_id == batch_delete_request.scene_id)

        # 时间范围筛选
        query = query.filter(
            AIWebMemoryHisModel.create_time >= parsed_start_date,
            AIWebMemoryHisModel.create_time <= parsed_end_date
        )

        # 状态筛选
        if batch_delete_request.status is not None:
            query = query.filter(AIWebMemoryHisModel.status == batch_delete_request.status)

        # 添加智能体筛选
        if batch_delete_request.agent_name:
            query = query.join(AIWebAgentModel, AIWebMemoryHisModel.agent_id == AIWebAgentModel.agent_id)
            query = query.filter(AIWebAgentModel.agent_name.like(f"%{batch_delete_request.agent_name}%"))
        elif batch_delete_request.agent_id:
            query = query.filter(AIWebMemoryHisModel.agent_id == batch_delete_request.agent_id)

        # 获取要删除的记忆信息
        memories_to_delete = query.all()

        if not memories_to_delete:
            return {"message": "没有找到符合条件的记忆", "deleted_count": 0, "cleared_sessions": 0}

        # 收集唯一的session信息用于清除内存记忆
        sessions_to_clear = {}
        for memory in memories_to_delete:
            session_key = f"{memory.scene_id}:{memory.agent_id}:{memory.session_id}:{memory.user_id}"
            if session_key not in sessions_to_clear:
                sessions_to_clear[session_key] = {
                    "scene_id": memory.scene_id,
                    "agent_id": memory.agent_id,
                    "session_id": memory.session_id,
                    "user_id": memory.user_id
                }

        # 执行删除
        deleted_count = query.count()  # 获取要删除的数量
        query.delete(synchronize_session=False)
        db.commit()

        # 清除相关会话的内存记忆
        cleared_sessions = 0
        try:
            from memory.MemoryManager import MemoryManager

            for session_info in sessions_to_clear.values():
                try:
                    memory_manager = MemoryManager(
                        db_session=db,
                        scene_id=session_info["scene_id"],
                        agent_id=session_info["agent_id"],
                        session_id=session_info["session_id"],
                        user_id=session_info["user_id"]
                    )

                    # 清除所有内存记忆
                    if memory_manager.clear_memory(clear_db=False, clear_mem0=True):
                        cleared_sessions += 1
                        print(f"✅ 成功清除session {session_info['session_id']} 的内存记忆")

                except Exception as session_error:
                    print(f"⚠️ 清除session {session_info['session_id']} 内存记忆失败: {session_error}")

        except Exception as memory_error:
            print(f"⚠️ 批量清除内存记忆失败: {memory_error}")

        return {
            "message": f"成功删除 {deleted_count} 条记忆，清除了 {cleared_sessions} 个会话的内存记忆",
            "deleted_count": deleted_count,
            "cleared_sessions": cleared_sessions
        }

    except HTTPException:
        # 重新抛出HTTP异常
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"批量删除失败: {str(e)}")


@router.put("/{memory_id}/status", summary="更新记忆状态")
async def update_memory_status(
        memory_id: int,
        status_update: AIWebMemoryHisStatusUpdate,
        db: Session = Depends(get_db_session)
):
    """更新记忆状态"""
    try:
        memory = db.query(AIWebMemoryHisModel).filter(AIWebMemoryHisModel.id == memory_id).first()

        if not memory:
            raise HTTPException(status_code=404, detail="记忆不存在")

        memory.update_status(status_update.status)
        db.commit()

        return {"message": "状态更新成功"}

    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"状态更新失败: {str(e)}")


@router.put("/{memory_id}/importance", summary="更新记忆重要程度")
async def update_memory_importance(
        memory_id: int,
        importance_update: AIWebMemoryHisImportanceUpdate,
        db: Session = Depends(get_db_session)
):
    """更新记忆重要程度"""
    try:
        memory = db.query(AIWebMemoryHisModel).filter(AIWebMemoryHisModel.id == memory_id).first()

        if not memory:
            raise HTTPException(status_code=404, detail="记忆不存在")

        memory.update_importance(importance_update.importance_level)
        db.commit()

        return {"message": "重要程度更新成功"}

    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"重要程度更新失败: {str(e)}")


@router.get("/statistics/overview", response_model=AIWebMemoryHisStatistics, summary="获取记忆统计信息")
async def get_memory_statistics(
        scene_id: Optional[str] = Query(None, description="场景ID筛选"),
        agent_id: Optional[str] = Query(None, description="智能体ID筛选"),
        scene_name: Optional[str] = Query(None, description="场景名称筛选"),
        agent_name: Optional[str] = Query(None, description="智能体名称筛选"),
        db: Session = Depends(get_db_session)
):
    """获取记忆统计信息"""
    try:
        # 基础查询
        base_query = db.query(AIWebMemoryHisModel)

        # 添加关联查询（如果需要按名称筛选）
        need_scene_join = scene_name is not None
        need_agent_join = agent_name is not None

        if need_scene_join:
            base_query = base_query.join(AIWebSceneModel, AIWebMemoryHisModel.scene_id == AIWebSceneModel.scene_id)
            base_query = base_query.filter(AIWebSceneModel.scene_name.like(f"%{scene_name}%"))
        elif scene_id:
            base_query = base_query.filter(AIWebMemoryHisModel.scene_id == scene_id)

        if need_agent_join:
            base_query = base_query.join(AIWebAgentModel, AIWebMemoryHisModel.agent_id == AIWebAgentModel.agent_id)
            base_query = base_query.filter(AIWebAgentModel.agent_name.like(f"%{agent_name}%"))
        elif agent_id:
            base_query = base_query.filter(AIWebMemoryHisModel.agent_id == agent_id)

        # 总数统计
        total_count = base_query.count()
        temporary_count = base_query.filter(AIWebMemoryHisModel.status == 1).count()
        daily_count = base_query.filter(AIWebMemoryHisModel.status == 2).count()
        permanent_count = base_query.filter(AIWebMemoryHisModel.status == 3).count()

        # 重要程度分布
        importance_distribution = {}
        for level in range(1, 6):
            count = base_query.filter(AIWebMemoryHisModel.importance_level == level).count()
            importance_distribution[level] = count

        # 最近活动统计（最近7天每天的新增数量）
        from datetime import timedelta
        recent_activity = []
        for i in range(7):
            date = datetime.now() - timedelta(days=i)
            start_date = datetime(date.year, date.month, date.day)
            end_date = start_date + timedelta(days=1)

            daily_count_recent = base_query.filter(
                and_(
                    AIWebMemoryHisModel.create_time >= start_date,
                    AIWebMemoryHisModel.create_time < end_date
                )
            ).count()

            recent_activity.append({
                "date": start_date.strftime("%Y-%m-%d"),
                "count": daily_count_recent
            })

        return AIWebMemoryHisStatistics(
            total_count=total_count,
            temporary_count=temporary_count,
            daily_count=daily_count,
            permanent_count=permanent_count,
            importance_distribution=importance_distribution,
            recent_activity=recent_activity
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")


@router.get("/session/{session_id}/memories", response_model=List[AIWebMemoryHisResponse], summary="获取对话相关记忆")
async def get_session_memories(
        session_id: str,
        limit: int = Query(50, ge=1, le=200, description="返回数量限制"),
        db: Session = Depends(get_db_session)
):
    """获取指定对话的所有相关记忆"""
    try:
        memories = db.query(AIWebMemoryHisModel).filter(
            AIWebMemoryHisModel.session_id == session_id
        ).order_by(desc(AIWebMemoryHisModel.create_time)).limit(limit).all()

        memory_list = []
        for memory in memories:
            memory_response = AIWebMemoryHisResponse(
                id=memory.id,
                scene_id=memory.scene_id,
                agent_id=memory.agent_id,
                session_id=memory.session_id,
                user_id=memory.user_id,
                his_text=memory.his_text,
                create_time=memory.create_time,
                update_time=memory.update_time,
                status=memory.status,
                importance_level=memory.importance_level,
                tags=memory.tags,
                annotation=memory.annotation,
                extra_info=memory.get_extra_info()
            )
            memory_list.append(memory_response)

        return memory_list

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取对话记忆失败: {str(e)}")
